package com.hdu.mockService.handler;

import com.hdu.mockService.annotation.RandomTime;
import com.hdu.mockService.utils.RandomDateTimeGenerator;
import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.List;

import static com.hdu.mockService.utils.PredictionUtils.unValidParam;
import static com.hdu.mockService.utils.ReflectionUtils.getFieldsByTargetAnnotation;

public class LocalDataTimeMockHandler implements IMockHandler {
    @Override
    public void partitionMock(Object mockObj) {
        List<Field> randomTimeFields = getFieldsByTargetAnnotation(mockObj.getClass(), RandomTime.class);
        if (CollectionUtils.isEmpty(randomTimeFields)) {
            return;
        }

        randomTimeFields.forEach(field -> {
            RandomTime randomTime = field.getAnnotation(RandomTime.class);
            field.setAccessible(true);
            try {
                field.set(
                        mockObj,
                        getRandomLocalDateTime(
                                randomTime.minTime(),
                                randomTime.maxTime(),
                                randomTime.timePattern()
                        )
                );
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        });
    }


    private LocalDateTime getRandomLocalDateTime(String min, String max, String pattern) {

        unValidParam(
                min == null || max == null || pattern == null,
                "min, max, pattern must not be null"
        );

        return RandomDateTimeGenerator.getRandomDateTime(min, max, pattern);
    }
}
